package org.zsqx.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.zsqx.bean.Dstype;
import org.zsqx.bean.Linkman;
import org.zsqx.bean.Town;
import org.zsqx.bean.UsrReport;
import org.zsqx.tools.ExcelTools;

import cDao.annotation.OrderByEnum;
import cDao.cache.CacheManager;


@Action(value="/reportAction",results={
		@Result(name="main",location="/login/main.jsp"),
		@Result(name="report",location="/login/disasterDetail.jsp"),
		@Result(name="list",location="/reportAction!reportList.action",type="redirect",params={"usrReport.reStatus","${usrReport.reStatus}"}),
		@Result(name="reportList",location="/login/reportList.jsp"),
		@Result(name="outputExcel",type="stream",params={"contentType","application/vnd.ms-excel","maximumSize","500000","inputName","excelStream","contentDisposition","attachment;filename=${fileNames}"}),
		@Result(name="detail",location="/login/reportDetail.jsp")
})
public class ReportAction extends BaseAction {
	private List<Dstype> dstypes;
	private List<Town> towns;
	private List<Linkman> linkmans;
	private List<UsrReport> reportList;
	private UsrReport usrReport;
	private static List<UsrReport> excelList=new ArrayList<UsrReport>();
	private InputStream excelStream;
	private String fileNames;
	
	public String reportList(){
		//清空缓存
		CacheManager.getInstance().clearAllCache();
		dstypes = rd.find(new Dstype());//灾害类型
		towns = rd.find(new Town()); //城镇
		linkmans = rd.find(new Linkman());//联系人
		if(null== usrReport){
			usrReport = new UsrReport();
			usrReport.setReStatus(0);
		}
		pageBean = rd.getPageBean(currentPage, rd.getCount(usrReport), pageSize);
		rd.setPageBean(pageBean).setOrderBy(OrderByEnum.DESC).setOrderByField("re_Time");
		reportList = rd.findByPage(usrReport);
		excelList=rd.find(usrReport);
		return "reportList";
	}
	public String reportClear(){
		int s = usrReport.getReStatus();
		if(s==1){
			usrReport.setReStatus(0);
		}else{
			usrReport.setReStatus(1);
		}
		rd.update(usrReport);
		return "list";
	}
	public String detail(){
		usrReport=(UsrReport) rd.findById(usrReport);
		return "detail";
	}
	public String addDisaster(){
		String ids=request.getParameter("ids");
		if (null!=ids||!"()".equals(ids)) {
			reportList=new ArrayList<UsrReport>();
			for (String id : ids.split(",")) {
				usrReport=new UsrReport();
				usrReport.setReNum(Integer.parseInt(id));
				usrReport=(UsrReport) rd.findById(usrReport);
				reportList.add(usrReport);
			}
		}
		return "report";
	}
	
	public String deleteRe(){
		rd.delete(usrReport);
		return "list";
	}
	
	public String outputExcel(){
		
//		if (excelList.size()>0) {
//			try {
//				String down_path=ExcelTools.writeExcelByJXL(absolute_path,excelList);
//				BufferedInputStream bis = null;
//				BufferedOutputStream bos = null;
//				OutputStream fos = null;
//				InputStream fis = null;
//				File uploadFile = new File(down_path);
//				fis = new FileInputStream(uploadFile);
//				bis = new BufferedInputStream(fis);
//				fos = response.getOutputStream();
//				bos = new BufferedOutputStream(fos);
//				String fileName=down_path.substring(down_path.lastIndexOf("\\")+1,down_path.length());
//				response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
//				int bytesRead = 0;
//				byte[] buffer = new byte[8192];
//				while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//					bos.write(buffer, 0, bytesRead);
//				}
//				bos.flush();
//				bos.close();
//				bis.close();
//				fis.close();
//				fos.flush();
//				fos.close();
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		return "outputExcel";
	}
	
	public List<UsrReport> getReportList() {
		return reportList;
	}
	public void setReportList(List<UsrReport> reportList) {
		this.reportList = reportList;
	}
	public UsrReport getUsrReport() {
		return usrReport;
	}
	public void setUsrReport(UsrReport usrReport) {
		this.usrReport = usrReport;
	}
	public List<Dstype> getDstypes() {
		return dstypes;
	}
	public void setDstypes(List<Dstype> dstypes) {
		this.dstypes = dstypes;
	}
	public List<Town> getTowns() {
		return towns;
	}
	public void setTowns(List<Town> towns) {
		this.towns = towns;
	}
	public List<Linkman> getLinkmans() {
		return linkmans;
	}
	public void setLinkmans(List<Linkman> linkmans) {
		this.linkmans = linkmans;
	}
	
	public InputStream getExcelStream() {
		String absolute_path=request.getRealPath("/");
		if(null== usrReport){   //默认导出未上报
			usrReport = new UsrReport();
			usrReport.setReStatus(0);
		}
		excelList=rd.find(usrReport);
		fileNames=ExcelTools.writeExcelByJXL(absolute_path,excelList)+".xls";
		String realPath="/login/excel/"+fileNames;
		System.out.println(realPath);
		InputStream in=null;
		try {
			in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
			if(null==in){
				System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");   
			}
		}catch (IllegalArgumentException e) {
			e.printStackTrace();
		}catch (IllegalStateException e) {
			e.printStackTrace();
		}finally{
			if(null!=in){
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return in;

	}
	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
	public String getFileNames() {
		return fileNames;
	}
	public void setFileNames(String fileNames) {
		this.fileNames = fileNames;
	}
	@Override
	public void validate() {
		if(usrReport!=null){
			if(usrReport.getReStatus()!=null&&usrReport.getReStatus().equals("")){
				usrReport.setReStatus(null);
			}
			if(usrReport.getReTown()!=null&&usrReport.getReTown().equals("")){
				usrReport.setReTown(null);
			}
			if(usrReport.getReType()!=null&&usrReport.getReType().equals("")){
				usrReport.setReType(null);
			}
			if(usrReport.getReMan()!=null&&usrReport.getReMan().equals("")){
				usrReport.setReMan(null);
			}
		}
		super.validate();
	}

}
